﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DataModel.Commands
{
    public static class KeyCommand
    {

        public static readonly DependencyProperty RegisteredKeyUpProperty = 
            DependencyProperty.RegisterAttached("RegisteredKeyUp", typeof(bool), typeof(KeyCommand),
            new PropertyMetadata(false));

        public static void SetRegisteredKeyUp(UIElement element, bool value)
        {
            element.SetValue(RegisteredKeyUpProperty, value);
        }
        public static bool GetRegisteredKeyUp(UIElement element)
        {
            return (bool)element.GetValue(RegisteredKeyUpProperty);
        }


        public static readonly DependencyProperty EnterKeyCommandProperty =
            DependencyProperty.RegisterAttached("EnterKeyCommand", typeof(ICommand), typeof(KeyCommand), new PropertyMetadata(null, RegisterKeyCommand));
        public static void SetEnterKeyCommand(UIElement element, ICommand value)
        {
            element.SetValue(EnterKeyCommandProperty, value);
        }
        public static ICommand GetEnterKeyCommand(UIElement element)
        {
            return (ICommand)element.GetValue(EnterKeyCommandProperty);
        }

        static void RegisterKeyCommand(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (!GetRegisteredKeyUp((UIElement)sender))
            {
                SetRegisteredKeyUp((UIElement)sender, true);
                ((UIElement)sender).KeyUp += OnKeyUp;
            }
        }

        static void OnKeyUp(object sender, KeyEventArgs e)
        {
            DependencyProperty DP = null;

            switch (e.Key)
            {
                case Key.Enter:
                    DP = EnterKeyCommandProperty;
                    break;
            }

            if (DP != null)
            {
                var Command = ((UIElement)sender).GetValue(DP) as ICommand;
                if (Command != null && Command.CanExecute(null))
                {
                    Command.Execute(null);
                }
            }
        }

        
    }
}
